﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace UCL.Web
{
    public class WebCaptchaHelper : ImageHelper, System.Web.SessionState.IRequiresSessionState
    {

        /// <summary>
        /// 输出文字图形
        /// </summary>
        /// <param name="response"></param>
        /// <param name="s"></param>
        public void WriteImage(HttpResponse response, string s)
        {
            response.ClearContent();
            response.ContentType = "image/Gif";
            response.BinaryWrite(base.GetBitmapForText(s));

        }

        /// <summary>
        /// 输出验证码,暂时不用
        /// </summary>
        /// <param name="page"></param>
        /// <param name="varName"></param>
        /// <param name="length"></param>
        private void WriteVerifyImage(System.Web.UI.Page page, string varName = "captcha", int length = 4)
        {
            string s = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            Random rnd = new Random();
            int[] arrPoint = new int[4] { rnd.Next(0, 62), rnd.Next(0, 62), rnd.Next(0, 62), rnd.Next(0, 62) };
            s = string.Format("{0}{1}{2}{3}", s[arrPoint[0]], s[arrPoint[1]], s[arrPoint[2]], s[arrPoint[3]]);
            System.Web.SessionState.HttpSessionState session = page.Session;
            session["verifyCode"] = s;
            this.WriteImage(page.Response, s);
        }
        public void WriteCaptcha(string varName = "captcha", int length = 4)
        {
            System.Web.HttpContext.Current.Response.Expires = 0;
            System.Web.HttpContext.Current.Response.CacheControl = "no-cache";

            CaptchaHelper cap = new CaptchaHelper();
            string code = cap.GenerateCheckCode();
            HttpContext.Current.Session[varName] = code;
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.ContentType = "image/PNG";
            HttpContext.Current.Response.BinaryWrite(cap.GetCheckCodeImage(code));
        }
    }
}
